package com.wang.spring.handler;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.wang.rest.RestServer;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

public class RestHandler extends HandlerInterceptorAdapter {
    private RestServer restServer;

    public RestHandler(DataSource dataSource) {
        Map<String, String> map = new HashMap<>();
        map.put("host", "localhost");
        map.put("port", "3306");
        map.put("database", "wdj");
        map.put("user", "root");
        map.put("password", "root");
        this.restServer = new RestServer(map, dataSource);
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String url = request.getServletPath();
        if(!url.startsWith("/rest")) return super.preHandle(request, response, handler);
        String method = request.getMethod().toLowerCase();
        String body = null;
        int length = request.getContentLength();
        if(length != -1) {
            byte[] bs = new byte[length];
            request.getInputStream().read(bs, 0, length);
            body = new String(bs);
        }
        RestServer.Request restReq = new RestServer.Request(url.substring("/rest".length()), method, body);
        Object resp = restServer.execute(restReq);
        JSONObject respJson = new JSONObject();
        respJson.put("code", 0);
        respJson.put("data", resp);
        String r = JSONObject.toJSONString(respJson, SerializerFeature.PrettyFormat);
        response.getWriter().write(r);
        return false;
    }
}
